package com.hoperay;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.servlet.http.HttpSession;

import com.hoperay.util.GeoJsonUtil;
import com.hoperay.util.GeoLocation;
import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.Constants;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.Address;
import com.liferay.portal.model.Contact;
import com.liferay.portal.model.ListType;
import com.liferay.portal.model.Phone;
import com.liferay.portal.model.User;
import com.liferay.portal.service.AddressLocalServiceUtil;
import com.liferay.portal.service.ClassNameLocalServiceUtil;
import com.liferay.portal.service.ListTypeServiceUtil;
import com.liferay.portal.service.PhoneLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
import com.slayer.model.AddressExt;
import com.slayer.model.City;
import com.slayer.service.AddressExtLocalServiceUtil;
import com.slayer.service.CityLocalServiceUtil;

public class RegistrationPortlet extends MVCPortlet {

	public void saveAddress(ActionRequest actionRequest,
			ActionResponse actionResponse) throws IOException, PortletException {

		User user = null;

		try {
			user = PortalUtil.getUser(actionRequest);
		} catch (PortalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		setUserAddress(user, actionRequest);
		setPhone(user, actionRequest, "primary");
		setPhone(user, actionRequest, "secondary");

		// put the fresh GEOLocation object back into session
		HttpSession session = PortalUtil.getHttpServletRequest(actionRequest)
				.getSession();
		session.setAttribute("USER_GEO_LOCATION", new GeoLocation(user));
	}

	public void savepopup(ActionRequest actionRequest,
			ActionResponse actionResponse) throws IOException, PortletException {
		User user = null;

		try {
			user = PortalUtil.getUser(actionRequest);
		} catch (PortalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		setUserLocation(user, actionRequest);

	}

	private void setUserLocation(User user, PortletRequest portletRequest) {
		// TODO Auto-generated method stub
		
		long cityId = ParamUtil.getLong(portletRequest, "city");
		long countryId = ParamUtil.getLong(portletRequest, "countryId");
		long regionId = ParamUtil.getLong(portletRequest, "regionId");
		String newCity = ParamUtil.getString(portletRequest, "otherCity");
		long addressId = ParamUtil.getLong(portletRequest, "addressId", 0l);
		
		Address address = null;
		AddressExt addressExt = null;
				
		if (addressId <= 0l) {
			try {
				addressId = CounterLocalServiceUtil.increment();
				addressExt = AddressExtLocalServiceUtil
						.createAddressExt(addressId);

				AddressExtLocalServiceUtil.addAddressExt(addressExt);
			} catch (SystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			address = AddressLocalServiceUtil.createAddress(addressId);
			address.setCreateDate(new java.util.Date());
			address.setNew(true);

			try {
				address = AddressLocalServiceUtil.updateAddress(address);
			} catch (SystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		try {
			address = AddressLocalServiceUtil.fetchAddress(addressId);
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		address.setModifiedDate(new java.util.Date());
		address.setCountryId(countryId);
		address.setRegionId(regionId);

		List<City> cities = new ArrayList<City>();
		try {
			cities = CityLocalServiceUtil.getService().getRegion_Cities(
					Long.valueOf(regionId));
		} catch (SystemException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		
		if (cities.size() == 0) {

			address.setCity(newCity);

			try {
				addressExt = AddressExtLocalServiceUtil
						.fetchAddressExt(addressId);
			} catch (SystemException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			City acity = null;
			long cityId1;
			try {
				cityId1 = CounterLocalServiceUtil.increment();
				acity = CityLocalServiceUtil.createCity(cityId1);
				acity.setCityId(cityId1);
				acity.setStatus(true);
				acity.setCityName(newCity);
				acity.setRegionId(regionId);
				addressExt.setCityId(cityId1);
				CityLocalServiceUtil.updateCity(acity);

			} catch (SystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		    } else {

			City cityOld = null;

			try {
				cityOld = CityLocalServiceUtil.getCity(cityId);
			} catch (PortalException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			} catch (SystemException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
			String cname = cityOld.getCityName();

			address.setCity(cname);
			try {
				addressExt = AddressExtLocalServiceUtil
						.fetchAddressExt(addressId);
			} catch (SystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			addressExt.setCityId(cityId);
		}
	
		try {
			AddressLocalServiceUtil.updateAddress(address);
			AddressExtLocalServiceUtil.updateAddressExt(addressExt);
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void setPhone(User user, ActionRequest actionRequest,
			String phoneType) {

		Date now = new Date();
		long phoneId = ParamUtil.getLong(actionRequest, phoneType + "PhoneId",
				0l);
		String phoneNumber = ParamUtil.getString(actionRequest, phoneType
				+ "Phone");
		boolean isMobile = ParamUtil.getBoolean(actionRequest, "is"
				+ toCamelCase(phoneType) + "Mobile", false);

		String type_ = isMobile ? "mobile-phone" : "other";

		Phone phone = null;

		if (phoneId <= 0l) {

			if (Validator.isNull(phoneNumber))
				return;

			try {
				phoneId = CounterLocalServiceUtil.increment();
			} catch (SystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			phone = PhoneLocalServiceUtil.createPhone(phoneId);
			phone.setCreateDate(now);
			phone.setNew(true);
			try {
				phone = PhoneLocalServiceUtil.updatePhone(phone);
			} catch (SystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		try {
			phone = PhoneLocalServiceUtil.fetchPhone(phoneId);
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		phone.setCompanyId(user.getCompanyId());
		phone.setUserId(user.getUserId());
		phone.setUserName(user.getFullName());
		phone.setClassNameId(ClassNameLocalServiceUtil
				.getClassNameId(Contact.class));
		phone.setClassPK(user.getContactId());
		phone.setModifiedDate(now);
		phone.setNumber(phoneNumber);
		phone.setPrimary(phoneType.equalsIgnoreCase("primary"));

		List<ListType> listTypes = null;
		try {

			listTypes = ListTypeServiceUtil.getListTypes(Contact.class
					.getName() + ".phone");

		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		for (ListType listType : listTypes) {

			if (listType.getName().equalsIgnoreCase(type_)) {
				phone.setTypeId(listType.getListTypeId());
				break;
			}
		}

		try {
			phone = PhoneLocalServiceUtil.updatePhone(phone);
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private String toCamelCase(String str) {
		// TODO Auto-generated method stub
		return str.substring(0, 1).toUpperCase() + str.substring(1);
	}

	private void setUserAddress(User user, PortletRequest portletRequest){

		long addressId = ParamUtil.getLong(portletRequest, "addressId", 0l);

		Address address = null;
		AddressExt addressExt = null;

		if (addressId <= 0l) {
			try {
				addressId = CounterLocalServiceUtil.increment();
				addressExt = AddressExtLocalServiceUtil.createAddressExt(addressId);

				AddressExtLocalServiceUtil.addAddressExt(addressExt);
			} catch (SystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			address = AddressLocalServiceUtil.createAddress(addressId);
			address.setCreateDate(new java.util.Date());
			address.setNew(true);

			try {
				address = AddressLocalServiceUtil.updateAddress(address);
			} catch (SystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		try {
			address = AddressLocalServiceUtil.fetchAddress(addressId);
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		address.setClassNameId(ClassNameLocalServiceUtil.getClassNameId(Contact.class));
		address.setClassPK(user.getContactId());
		address.setUserId(user.getUserId());
		address.setCompanyId(user.getCompanyId());
		address.setModifiedDate(new java.util.Date());
		address.setUserName(user.getFullName());
		address.setPrimary(true);

		List<ListType> listTypes;
		try {
			listTypes = ListTypeServiceUtil.getListTypes(Contact.class
					.getName() + ".address");
			for (ListType listType : listTypes) {
				if (listType.getName().equalsIgnoreCase("personal")) {
					address.setTypeId(listType.getListTypeId());
					break;
				}
			}
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		 
		long cityId = ParamUtil.getLong(portletRequest, "city");
		String street1 = ParamUtil.getString(portletRequest, "street1");
		String street2 = ParamUtil.getString(portletRequest, "street2");
		String zip = ParamUtil.getString(portletRequest, "zip");
		long countryId = ParamUtil.getLong(portletRequest, "countryId");
		long regionId = ParamUtil.getLong(portletRequest, "regionId");
		String newCity = ParamUtil.getString(portletRequest, "otherCity");
		
		address.setStreet1(street1);
		address.setStreet2(street2);
		address.setZip(zip);
		address.setCountryId(countryId);
		address.setRegionId(regionId);

		List<City> cities = new ArrayList<City>();
		try {
				cities = CityLocalServiceUtil.getService().getRegion_Cities(Long.valueOf(regionId));
			} catch (SystemException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
		if (cities.size() == 0) {
			
				address.setCity(newCity);
				
				try {
					addressExt	= AddressExtLocalServiceUtil.fetchAddressExt(addressId);
				} catch (SystemException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				City acity = null;
				long cityId1;
				try {
					 	cityId1 = CounterLocalServiceUtil.increment();
		
						acity = CityLocalServiceUtil.createCity(cityId1);
						acity.setCityId(cityId1);
						acity.setStatus(true);
						acity.setCityName(newCity);
						acity.setRegionId(regionId);
						addressExt.setCityId(cityId1);
						
						CityLocalServiceUtil.updateCity(acity);
						
				 	}catch (SystemException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				 	}
			 
		} else {
			
					City cityOld = null;
					
					try {
						cityOld = CityLocalServiceUtil.getCity(cityId);
					} catch (PortalException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					} catch (SystemException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
					String cname = cityOld.getCityName();
					
					address.setCity(cname);
					try {
						addressExt = AddressExtLocalServiceUtil.fetchAddressExt(addressId);
					} catch (SystemException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					addressExt.setCityId(cityId);
			
		}

		try {
			AddressExtLocalServiceUtil.updateAddressExt(addressExt);
			AddressLocalServiceUtil.updateAddress(address);
			
			
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void serveResource(ResourceRequest resourceRequest,
			ResourceResponse resourceResponse) throws PortletException,
			IOException {

		String cmd = resourceRequest.getParameter(Constants.CMD);

		if (cmd != null && cmd.equalsIgnoreCase("get-regions")) {

			GeoJsonUtil.getRegions(resourceRequest, resourceResponse);
		}

		else if (cmd != null && cmd.equalsIgnoreCase("get-cities")) {
			GeoJsonUtil.getCities(resourceRequest, resourceResponse);
		}
	}
}